import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '@/views/Login/index.vue'
import Welcome from '@/views/Welcome/index.vue'
import NotFound from '@/views/NotFound/index.vue'
import Test from '@/views/Test/index.vue'
import Layout from '@/views/Layout/index.vue'
import Users from '@/views/Users/index.vue'
import Rights from '@/views/Rights/index.vue'
import Goods from '@/views/Goods/index.vue'
import Roles from '@/views/Roles/index.vue'
import Categories from '@/views/Categories/index.vue'
import Params from '@/views/Params/index.vue'
import GoodsAdd from '@/views/Goods/components/GoodsAdd.vue'
import GoodsEdit from '@/views/Goods/components/GoodsEdit.vue'
import Orders from '@/views/Orders/index.vue'
import Reports from '@/views/Reports/index.vue'
import { message } from '@/utils/functions'
// 引入pinia中的用户模块
import { useUserStore } from '@/stores/user'
// 写在此处有问题，得不到一个正确pinia实例
// const userStore = useUserStore()
// console.log(userStore);
const routes = [
    {
        path: '/',
        component: Layout,
        redirect: '/welcome',
        children: [
            { path: '/welcome', component: Welcome },
            { path: '/users', component: Users },
            { path: '/rights', component: Rights },
            { path: '/goods', component: Goods },
            { path: '/roles', component: Roles },
            { path: '/categories', component: Categories },
            { path: '/params', component: Params },
            { path: '/goods/add', component: GoodsAdd },
            { path: '/goods/:id', component: GoodsEdit },
            { path: '/orders', component: Orders },
            { path: '/reports', component: Reports }
        ]
    },
    { path: '/login', name: 'login', component: Login },
    { path: '/test', component: Test },
    //404页面
    {
        path: '/:pathMatch(.*)*',
        name: '404', // 路由名称，为了配合路由导航守卫
        component: NotFound
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

// 配置全局前置守卫，做相应的路由的拦截
router.beforeEach((to, from, next) => {
    // 获取pinia实例
    const userStore = useUserStore()
    // 其中login路由和404路由是不需要做登录校验了，直接放行
    if (to.path === '/login' || to.name === '404') {
        return next()
    }
    // 其他路由都做登录校验
    const token = userStore.token
    if (!token) {
        // 如果没有登录，就跳转到登录页面
        message('warning', '请先登录')
        return next('/login')
    }
    next()

})

export default router